package com.example.androidmainshixun.view;

import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.androidmainshixun.R;
import com.example.androidmainshixun.base.BaseFragment;
import com.example.androidmainshixun.database.DBHelper;
import com.example.androidmainshixun.entity.User;
import com.example.androidmainshixun.utils.SpUtils;

public class ActivityPassEditFragment extends BaseFragment {
    private Button mpass_edit_ok;
    private EditText met_account;
    private TextView met_password;
    private SpUtils mSpUtils;


    private boolean allInputNotEmpty(String... inputStrings) {
        for (int i = 0; i < inputStrings.length; i++) {
            if (TextUtils.isEmpty(inputStrings[i])) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pass_edit_fragment;
    }

    @Override
    protected void initView() {
        mpass_edit_ok = mView.findViewById(R.id.pass_edit_ok);
        met_account = mView.findViewById(R.id.et_account);
        met_password = mView.findViewById(R.id.et_password);
        met_account.setKeyListener(null);
        mSpUtils = new SpUtils(mContext);

        int loginId = mSpUtils.getInt(SpUtils.LOGIN_KEY, -1);
        if (loginId >= 0) {
            //根据id查询当前登录学生的信息
            User user = DBHelper.getInstance(mContext).getUserById(loginId);
            if (user != null) {
                //将当前登录的学生信息显示在界面上
                met_account.setText(user.getUsername());
            }
        }
    }


    @Override
    protected void initListener() {
        mpass_edit_ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String changedpassword = met_password.getText().toString();
                String username=met_account.getText().toString();
                if (v.getId() == R.id.pass_edit_ok) {
                    if (allInputNotEmpty(changedpassword,username)) {
                        User user = new User();
                        user.setPass(changedpassword);
                        user.setUsername(username);
                        int id = (int) DBHelper.getInstance(getContext()).UpdatePass(user);
                        if (id >= 0) {
                            Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                            met_password.setText("");
                        } else {
                            Toast.makeText(getContext(), "修改失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            }
        });
    }
}